package village.rainbow.dailyscene.util;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import village.rainbow.dailyscene.datamodel.DataRow;
import village.rainbow.dailyscene.datamodel.DataTable;
import android.annotation.SuppressLint;
import android.telephony.PhoneNumberUtils;


@SuppressLint("SimpleDateFormat")
public class StringUtil {
	
	public static String checkSpecialCharacter(String value) {
		String retVal = value;
		retVal = retVal.replaceAll("&amp;", "&"); 
		retVal = retVal.replaceAll("&quot;","\""); 		// &#034;
//		retVal = retVal.replaceAll("&#039;","&apos;");  // &#039; = &apos;
		retVal = retVal.replaceAll("&#039;","\'"); 		// &#039; = &apos;
		retVal = retVal.replaceAll("&lt;","<");  		// &#060;
		retVal = retVal.replaceAll("&gt;",">");  		// &#062;
		return retVal;
	}
	

	public static String Unit = "";

	public static String changeGroupName(String num) {
		String str;
		int asc = 0;
		if (num.equals("")) {
			str = "";
		} else {
			asc = Integer.parseInt(num) + 64;
			str = Character.toString((char)asc);
		}
		return str;
	}
	/**
	 *  yyyyMMddHHmmss
	 * @param time
	 * @param dateFormat
	 * @return
	 */
	public static String getTimeString(long time, String dateFormat)
	{
		Date date;
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		date = new Date(time);
		return sdf.format(date);
	}


	// ---------------- ?�래???�젠�?주석???�겠�?.. --------------- //
	public static String toBusinessPattern(String orgStr){
		if(orgStr.length() < 10)
			return orgStr;
		String businessNo = orgStr.substring(0, 3) + "-" + orgStr.substring(3, 5) + "-" + orgStr.substring(5);
		return businessNo;

	}

	public String s() {
		String returnStr = null;
		return returnStr;
	}

	public static String createYearString(String year){
		if(year.length() != 2){
			return year;
		}
		else{
			if(Integer.parseInt(year) > 90){
				return "19" + year;
			}else{
				return "20" + year;
			}
		}
	}

	public static String removeTab(String sourceStr){
		return sourceStr.replaceAll("\t", " ");
	}

	public static boolean isEmpty(String str) {
		if(str == null || str.equals(""))
			return true;

		return false;
	}

	public static String converToAsterisk(String pwd){

		char[] pwdChar = pwd.toCharArray();
		String asterisk = "";

		for(int i=0; i<pwdChar.length; i++){
			asterisk += "*";
		}

		return asterisk;
	}
	
	/**
	 * yyyyMMdd
	 * @return
	 */
	public static String previousDay(String date, int field, int value){
		Calendar calendar = Calendar.getInstance();
		if(date.length() != 8)
			return "";
		int orgyear = Integer.parseInt(date.substring(0, 4));
		int orgmonth = Integer.parseInt(date.substring(4, 6))-1;
		int orgdayOfMonth = Integer.parseInt(date.substring(6, 8));
		calendar.set(orgyear, orgmonth, orgdayOfMonth);
		calendar.add(field, value);
		String year = calendar.get(Calendar.YEAR) + "";
		String month = addZero(calendar.get(Calendar.MONTH) + 1);
		String day = calendar.get(Calendar.DAY_OF_MONTH) + "";
		return year + month + day;
	}

	/**
	 * yyyyMMdd
	 * @return
	 */
	public static String currentDate(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		return sdf.format(new Date());		
	}
	
	public static String currentTime(){
		SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
		return sdf.format(new Date());
	}

	public static String currentDate(String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(new Date());
	}
	
	public static String getDayOfWeek(String yyyyMMdd){
		try{
			if(yyyyMMdd.length() == 6)
				yyyyMMdd = "20" + yyyyMMdd;
			
			if(yyyyMMdd.length() != 8)
				return yyyyMMdd;
			
			Calendar cal= Calendar.getInstance ();
			int year = Integer.parseInt(yyyyMMdd.substring(0, 4));
			int month = Integer.parseInt(yyyyMMdd.substring(4, 6)) - 1; // 1빼줘야함 January 는 0부터 시작함
			int date = Integer.parseInt(yyyyMMdd.substring(6));
			
		    cal.set(Calendar.YEAR, year);
		    cal.set(Calendar.MONTH, month);
		    cal.set(Calendar.DATE, date);
		    
		    String dayOfWeek = "";
		    
		    switch (cal.get(Calendar.DAY_OF_WEEK)){
		    case 1:
		    	dayOfWeek = "일";
		        break;
		    case 2:
		    	dayOfWeek = "월";
		        break;
		    case 3:
		    	dayOfWeek = "화";
		        break;
		    case 4:
		    	dayOfWeek = "수";
		        break;
		    case 5:
		    	dayOfWeek = "목";
		        break;
		    case 6:
		    	dayOfWeek = "금";
		        break;
		    case 7:
		    	dayOfWeek = "토";
		        break;
		    }
			return dayOfWeek;
		}catch(Exception e){
			return yyyyMMdd;
		}
	}
	
	public static String addDate(String date, int adddate, String pattern) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		Date dt = sdf.parse(date);
		Calendar cl = Calendar.getInstance();
		cl.setTime(dt);
		cl.add(Calendar.DATE, adddate);
		String dd = sdf.format(cl.getTime());

		return dd;
	}

	public static String nvl(String data, String def) {
		if(data == null) {
			return def;
		}

		return data;
	}
	public static String nvl(Object data, String def) {
		if(data == null)
			return def;
		if (data instanceof String)
		{
			String result = (String)data;
			if (result.isEmpty())
				return def;
			else
				return result;
		}
		else
			return def;
	}
	public static String mvl(String data, String def) {
		if(StringUtil.isEmpty(data)) {
			return def;
		}

		return data;
	}

	public static String TimeFormat(String s) {
		if (s == null)
			return "";

		String str = null;
		if (s.length() == 4) {
			str = s.substring(0, 2) + ":" + s.substring(2, 4);
		} else if (s.length() == 6)
			str = s.substring(0, 2) + ":" + s.substring(2, 4) + ":"
					+ s.substring(4, 6);
		else
			str = s;

		return str;
	}
	
	public static String DateFormat(String s) {
		return DateFormat(s, ".");
	}
	
	public static String DateFormat(String s, String delimiter){
		if (s == null || s.length() < 6 )
			return "";

		String str = null;

		try {
			s = s.trim();
			if (s.length() == 6 ) {
				str = s.substring(0, 2) + delimiter + s.substring(2, 4) + delimiter
						+ s.substring(4, s.length());

			}else{
				str = s.substring(0, 4) + delimiter + s.substring(4, 6) + delimiter
						+ s.substring(6, s.length());
			}

		} catch (Exception e) {
			e.printStackTrace();
			str = s;
		}
		return str;
	}

	public static String CurrentYear(){
		Calendar c = Calendar.getInstance();
		return c.get(Calendar.YEAR) + "";		
	}
	public static String CurrentMonth(){
		Calendar c = Calendar.getInstance();
		return addZero(c.get(Calendar.MONTH) + 1);		
	}
	public static String CurrentDay(){
		Calendar c = Calendar.getInstance();
		return c.get(Calendar.DAY_OF_MONTH) + "";		
	}

	public static String PhoneNo(String s) {
		if (s == null || s.length() < 6)
			return "";
		return PhoneNumberUtils.formatNumber(s);
	}

	public static String dashRemover(String s) {
		String[] arr = s.split("-");
		s = arr[0] + arr[1];
		return s;
	}

	public static String addZero(String a){
		if(!isDigit(a)){
			return a;
		}else{
			int parseToInt = Integer.parseInt(a);
			return addZero(parseToInt);	
		}
	}

	public static String addZero(int a) {

		String s = null;
		if (a < 10) {
			s = "0" + Integer.toString(a);
		} else {
			s = Integer.toString(a);
		}
		return s;
	}

	public static String dayMonthAdderString(String s) {

		int a = Integer.parseInt(s);
		a += 1;
		s = Integer.toString(a);

		return s;

	}

	public static int addMonthAdderInt(int i) {

		i += 1;

		return i;
	}

	public static String YMDHMS(String s) {
		if (s == null || s.length() < 13)
			return "";

		String t = "";

		t = s.substring(0, 4) + "." + s.substring(4, 6) + "."
				+ s.substring(6, 8) + "  " + s.substring(8, 10) + ":"
				+ s.substring(10, 12) + ":" + s.substring(12, 14);

		return t;

	}

	public static String YMDHMS2(String s) {
		if (s == null || s.length() < 14)
			return "";

		String t = "";

		t = s.substring(0, 4) + "." + s.substring(4, 6) + "."
				+ s.substring(6, 8) + "  " + s.substring(8, 10) + ":"
				+ s.substring(10, 12) + ":" + s.substring(12, 14);

		return t;

	}

	// �޷°���
	public static String toChangeDate(String year, String month, String day) {
		String str = "";
		if (Integer.parseInt(month) > 1) {
			month = Integer.toString(Integer.parseInt(month) - 1);
		} else {
			if (Integer.parseInt(month) == 1) {
				month = "12";
				year = Integer.toString(Integer.parseInt(year) - 1);
			}
		}
		if (month.length() < 2) {
			month = "0" + month;
		}
		str = year + month + day;
		return str;
	}

	public static String toNumberString(String data, String format) {
		String returnVal = "";

		if (format == null)
			format = "#,###";
		if (data == null || data.trim().equals(""))
			return "";
		try {
			DecimalFormat df = new DecimalFormat(format);
			returnVal = df.format(Double.parseDouble(data));
		} catch (Exception e) {
			System.err.println("StringUtil.toNumberString() " + e.getMessage());
		}

		return returnVal;
	}
	public static String commaSplit(int source) {
		return commaSplit(source + "");
	}
	public static String commaSplit(String source) {
		try {
			if (source != null)
				source = source.trim();

			if (source == null || source.length() <= 3)
				return source;
			String sign = "";
			if (source.indexOf('-') > -1) {
				sign = "-";
				source = source.substring(1);
			}
			String sourceExceptPoint = source;
			String sourcePoint = "";
			if (source.indexOf(".") > -1) {
				sourceExceptPoint = source.substring(0, source.indexOf("."));
				sourcePoint = source.substring(source.indexOf("."));
			}
			char[] sourceArr = sourceExceptPoint.toCharArray();
			char[] reverseArr = new char[sourceArr.length];
			for (int i = 0; i < sourceArr.length; i++) {
				reverseArr[reverseArr.length - i - 1] = sourceArr[i];
			}
			char[] destArr = new char[reverseArr.length
			                          + (reverseArr.length - 1) / 3];
			int destIdx = destArr.length - 1;
			for (int i = 1; i <= reverseArr.length; i++) {
				destArr[destIdx] = reverseArr[i - 1];
				destIdx--;
				if (destIdx != -1 && (i % 3) == 0) {
					destArr[destIdx] = ',';
					destIdx--;
				}
			}
			return sign + String.valueOf(destArr) + sourcePoint;
		} catch (Exception x) {
			x.printStackTrace();
			return source;
		}
	}

	public static String showMoney(Object numO){
		if(numO == null)
			return showNum("0");
		else if(!(numO instanceof String)){
			return showNum(numO);
		}else if(isDigit(numO.toString())){
			int money = Integer.parseInt(numO.toString());
			return showNum(money + "");
		}else if(isNumber(numO.toString())){
			double money = Double.parseDouble(numO.toString());
			int m = (int)money;
			return showNum(m + "");
		}else{
			return showNum(numO);
		}
	}

	public static String showNum(Object numO) {
		if (numO == null)
			return "0";
		String num = String.valueOf(numO);
		if (num.trim().equals(""))
			return "0";
		// return toNumberString(num, null);
		return commaSplit(num);
	}

	public static DataTable calcPercentage(String calcRowKey, DataTable table){

		float calcSum = 0;
		for(DataRow row : table){
			String val = row.get(calcRowKey, "0").toString();
			if(isDigit(val) || isNumber(val)){
				calcSum += Float.parseFloat(val);
			}
		}
		for(int i=0; i<table.size(); i++){
			DataRow row = table.get(i);
			float v = 0;
			String val = row.get(calcRowKey, "0").toString();
			if(isDigit(val) || isNumber(val)){
				v = Float.parseFloat(val);
				v = (v/calcSum)*100;
			}
			row.put("PERCENT", (int)v);
			table.remove(i);
			table.add(i, row);
		}
		return table; 
	}

	public static String doubleTimeFormat(String str){
		String returnStr = "";
		String[] tempStr = str.split("-");

		if (tempStr.length == 1 && str.length() == 1) {
			return "0" + str;
		}else if (tempStr.length == 1 && str.length() == 2) {
			return str;
		}

		if (tempStr[1].length() != 2) {
			tempStr[1] = "0" + tempStr[1];
		}
		if (tempStr[2].length() != 2) {
			tempStr[2] = "0" + tempStr[2];
		}
		returnStr = tempStr[0] + "-" + tempStr[1] + "-" + tempStr[2];

		return returnStr;
	}

	public static String removePattern(String source, String pattern){
		if(source.length() == 0)
			return "";

		StringBuilder sb = new StringBuilder();
		if(source.indexOf(pattern) == -1){
			return source;
		}

		String[] bb = source.split(pattern);
		for(int i=0; i<bb.length; i++){
			sb.append(bb[i]);
		}

		return sb.toString();
	}

	public static String businessNumber(String no) {

		String a = no.substring(0, 3);
		String b = no.substring(3, 5);
		String c = no.substring(5);

		return a + "-" + b + "-" + c;
	}

	public static String stringDelimiter(String origin, char delim, int digit, char hiddenString, int... hiddenIndex){
		StringBuilder bulider = new StringBuilder();
		int weight = 1;
		for(char c : origin.toCharArray()){
			int length = bulider.length();
			int seperatorIndex = (digit*weight) + (weight-1);
			if(length == seperatorIndex){
				bulider.append(delim);
				weight++;
			}

			boolean isHidden = false;
			for(int index : hiddenIndex){
				if(weight == index){
					bulider.append(hiddenString);
					isHidden = true;
					break;
				}
			}

			if(!isHidden)
				bulider.append(c);
		}

		return bulider.toString();
	}

	/**
	 * ?�니코드?��? ?�닌�??�별
	 * @param str
	 * @return
	 */
	public static boolean isUnicode(String str){
		boolean isUnicode = true;
		for(int i=0; i<str.length(); i++){
			char c = str.charAt(i);
			if(!Character.isUnicodeIdentifierPart(c)){
				isUnicode = false;
				break;
			}
		}
		return isUnicode;
	}

	/**
	 * ?�어??�?��중에 ?��????�는�??�별
	 * @param str
	 * @return
	 */
	public static boolean isHanguel(String str){
		boolean isHanguel = false;
		for(int i=0; i<str.length(); i++){
			char c = str.charAt(i);
			isHanguel = isHanguel || (Character.getType(c) == 5 ? true : false);
		}
		return isHanguel;
	}

	/**
	 * Float??별도??메서?�로 ?�별.. ???�거 짱나??.
	 * Integer �?parsing ?????�는�??�별
	 * @param str
	 * @return
	 */
	public static boolean isDigit(String str){
		if(str == null)
			return false;

		boolean isDigit = true;
		if(str.length() == 0)
			return false;

		for(int i=0; i<str.length(); i++){
			char c = str.charAt(i);
			isDigit = isDigit && Character.isDigit(c) && (c == '.' ? true : false);
		}
		return isDigit;
	}

	public static boolean isNumber(String str){
		boolean isNumber = false;

		try{
			Double.parseDouble(str);
			isNumber = true;
		}catch(Exception e){
			e.printStackTrace();
		}

		return isNumber;
	}
	
	public static String MID(String org, int iFirst, int nCount){
		
		if(iFirst < 0 || nCount < 0)
			return org;
		
		StringBuilder builder = new StringBuilder();
		int stack = 0;
		for(int i=0; i<org.length(); i++){
			if(i < iFirst)
				continue;
			if(nCount <= stack)
				continue;
			stack++;
			char c = org.charAt(i);
			builder.append(c);
		}
		return builder.toString();
	}

	public static String LPAD(String source, int size, char paddingChar){
		StringBuilder builder = new StringBuilder();
		int gab = size - source.length();
		if(gab < 0)
			return source;
		for(int i=0; i<gab; i++){
			builder.append(paddingChar);
		}
		builder.append(source);
		return builder.toString();
	}

	public static String RPAD(String source, int size, char paddingChar){
		StringBuilder builder = new StringBuilder();
		int gab = size - source.length();
		if(gab < 0)
			return source;
		builder.append(source);
		for(int i=0; i<gab; i++){
			builder.append(paddingChar);
		}
		return builder.toString();
	}
	
	public static String getSumNumber(Object val1, Object val2)
	{
		int num1 = 0, num2 = 0;

		if (val1 == null || isNumber(nvl(val1, "0")) == false)
			num1 = 0;
		else
			num1 = (int)Double.parseDouble((String)val1);
		if (val2 == null || isNumber(nvl(val2, "0")) == false)
			num2 = 0;
		else
			num2 = (int)Double.parseDouble((String)val2);

		return (num1 + num2) + "";
	}

}